package com.only4play.httpapt.support.api.impl;

import com.google.gson.reflect.TypeToken;
import com.only4play.httpapt.common.json.OpHttpAptGsonBuilder;
import com.only4play.httpapt.support.api.JpPostService;
import com.only4play.httpapt.support.api.JsonPlaceholderService;
import com.only4play.httpapt.support.bean.posts.JpPostAddReq;
import com.only4play.httpapt.support.bean.posts.JpPostAddResp;
import com.only4play.httpapt.support.bean.posts.JpPostInfo;
import com.only4play.httpapt.support.bean.posts.JpPostSearchResp;
import com.only4play.httpapt.support.constant.JsonPlaceholderConstants;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * @author liyuncong
 * @version 1.0
 * @file JpPostServiceImpl
 * @brief JpPostServiceImpl
 * @details JpPostServiceImpl
 * @date 2024-08-16
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-08-16               liyuncong          Created
 */

@RequiredArgsConstructor
public class JpPostServiceImpl implements JpPostService {
    private final JsonPlaceholderService mainService;

    @Override
    public JpPostSearchResp getPosts() throws Exception {
        String apiUrl = this.mainService.getConfigStorage().getApiUrl(JsonPlaceholderConstants.Posts.GET_POSTS);
        String response = this.mainService.get(apiUrl, null);
        List<JpPostInfo> posts = OpHttpAptGsonBuilder.create().fromJson(response, new TypeToken<>() {
        });
        return new JpPostSearchResp(posts);
    }

    @Override
    public JpPostInfo getPost(Integer postId) throws Exception {
        String apiPath = String.format(JsonPlaceholderConstants.Posts.GET_POST, postId);
        String apiUrl = this.mainService.getConfigStorage().getApiUrl(apiPath);
        String response = this.mainService.get(apiUrl, null);
        return JpPostInfo.fromJson(response);
    }

    @Override
    public JpPostAddResp addPost(JpPostAddReq addReq) throws Exception {
        String apiUrl = this.mainService.getConfigStorage().getApiUrl(JsonPlaceholderConstants.Posts.ADD_POST);
        String response = this.mainService.post(apiUrl, addReq.toJson());
        return JpPostAddResp.fromJson(response);
    }
}
